package com.guli.oss.service.impl;

import com.guli.oss.service.FileService;
import com.guli.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile file) {

        /*String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        // 不存在则创建bucket
        if (!ossClient.doesBucketExist(bucketName)){
            ossClient.createBucket(bucketName);
            // 权限为公共
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }*/

        // 本地文件上传仓库
        String localBucketPath = ConstantPropertiesUtil.LOCAL_BUCKET_PATH;
        String nginxProxyUrl = ConstantPropertiesUtil.NGINX_PROXY_URL;

        try {
//            InputStream inputStream = file.getInputStream();
            // 日期当做文件夹    joda日期类
            String filePath = new DateTime().toString("yyyy/MM/dd");
            // uuid当做文件名
            String originalFilename = file.getOriginalFilename();
            String fileTypeName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuidStr = UUID.randomUUID().toString().replaceAll("-", "");
            // 日期文件夹 + 文件名
            String newFileName = filePath + "/" + uuidStr + fileTypeName;

            /*// 阿里云oss
            ossClient.putObject(bucketName, newFileName, inputStream);
            ossClient.shutdown();
            return "http://" + bucketName + "." + endPoint + "/" + newFileName;*/

            // 传到本地
            String localFilePath = localBucketPath + "/" + newFileName;
            File localFile = new File(localFilePath);
            // 如果含有目录则创建目录
            if (!localFile.getParentFile().exists()) localFile.getParentFile().mkdirs();
            file.transferTo(localFile);
            // 返回nginx代理地址
            return nginxProxyUrl +"/"+ newFileName;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
